package com.wyj.utils

import android.content.Context
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.qmuiteam.qmui.util.QMUIReflectHelper
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.Serializable
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

class XXPermissionsResult : Serializable {
    var permissions = ArrayList<String>()
    var isAll = false
    var hasNever = false
    var grantedPermissions = ArrayList<String>()
    var deniedPermissions = ArrayList<String>()
    suspend fun checkPermissions(context: Context): Int {
        var result = 0
        withContext(Dispatchers.Main) {
            if (deniedPermissions.size > 0) {
                result = if (hasNever) {
                    QMUIDialogHelper.createTipDialog(context, msg = "为保证APP正常运行，请到权限管理中打开被拒绝的权限", okClick = QMUIDialogAction.ActionListener { dialog, _ ->
                        dialog.dismiss()
                        XXPermissions.startPermissionActivity(context, deniedPermissions)
                    }).show()
                    2
                } else {
                    1
                }
            }
        }
        return result
    }
}

object XXPermissionsHelper {
    /***
     * 使用这个方法一定要在混淆配置里keep下XXPermission的包名，要不然反射找不到他的私有类，用不了
     */
    suspend fun requestAsync(context: Context, vararg permissions: String?): XXPermissionsResult = suspendCoroutine {
        val result = XXPermissionsResult()
        val clazz = Class.forName("com.hjq.permissions.PermissionUtils")
        result.permissions.addAll(permissions.filterNotNull())
        try {
            QMUIReflectHelper.invokeStaticMethod<Void>(clazz, "optimizeDeprecatedPermission", arrayOf(List::class.java), arrayOf(result.permissions))
        } catch (e: Exception) {
            it.resumeWithException(e)
        }
        /*这里不要传自己反射得来的permissionList*/
        XXPermissions.with(context).permission(arrayOf(*permissions)).request(object : OnPermissionCallback {
            private fun checkRequestSuccess() {
                if (result.permissions.size == result.deniedPermissions.size + result.grantedPermissions.size) {
                    it.resume(result)
                }
            }

            override fun onGranted(permissions: MutableList<String>, all: Boolean) {
                permissions?.forEach {
                    if (!result.grantedPermissions.contains(it)) {
                        result.grantedPermissions.add(it)
                    }
                }
                result.isAll = all
                if (all) {
                    it.resume(result)
                } else {
                    checkRequestSuccess()
                }
            }

            override fun onDenied(permissions: MutableList<String>, never: Boolean) {
                permissions?.forEach {
                    if (!result.deniedPermissions.contains(it)) {
                        result.deniedPermissions.add(it)
                    }
                }
                if (never) {
                    result.hasNever = true
                }
                checkRequestSuccess()
            }
        })
    }
}